package com.baiye.www.proxyHandler;

import com.baiye.www.channel.ChannelContainer;
import com.baiye.www.message.RpcRequestMessage;
import io.netty.channel.ChannelFuture;
import io.netty.util.concurrent.DefaultPromise;
import lombok.extern.slf4j.Slf4j;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;

/**
 * @author GUOZHIPENG
 * @version 1.0
 * @date 2021/12/1 20:32
 */
@Slf4j
public class ServiceInvocationHandler implements InvocationHandler {
    private String className;
    public ServiceInvocationHandler(String className) {
        this.className=className;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        long sequenceId=System.currentTimeMillis();
        RpcRequestMessage msg = new RpcRequestMessage(
                sequenceId,
                className,
//                serviceClass.getName(),
                method.getName(),
                method.getReturnType(),
                method.getParameterTypes(),
                args
        );
        ChannelFuture channelFuture = ChannelContainer.getChannel().writeAndFlush(msg);
        DefaultPromise<Object> promise = new DefaultPromise<>(ChannelContainer.getChannel().eventLoop());
        RpcResponseMessageHandler.PROMISE_MAP.put(sequenceId, promise);
        promise.await();
        if(promise.isSuccess()){
            return promise.getNow();
        }else {
            // 调用失败
            log.error("An error occurred when the call returned");
            throw new RuntimeException(promise.cause());
        }

    }
}
